package leetcode.recursive;

import java.util.ArrayList;
import java.util.List;

//22. 括号生成
public class GenerateParenthesis {
    public static void main(String[] args) {
        GenerateParenthesis generateParenthesis = new GenerateParenthesis();
        System.out.println(generateParenthesis.generateParenthesis(3));
    }

    //做减法，也可以做加法
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        // 左右都是n
        dfs("", res, n, n);
        return res;
    }

    // 因为每一次尝试，都使用新的字符串变量，所以无需回溯
    private void dfs(String curStr, List<String> res, int left, int right) {
        if (left == 0 && right == 0) {
            res.add(curStr);
            return;
        }
        // 剪枝（如图，左括号可以使用的个数严格大于右括号可以使用的个数，才剪枝，注意这个细节）
        if (left > right) {
            return;
        }
        if (left > 0) {
            dfs(curStr + "(", res, left - 1, right);
        }
        if (right > 0) {
            dfs(curStr + ")", res, left, right - 1);
        }
    }

    // 二战 --- 回溯
    public List<String> generateParenthesis2(int n) {
        List<String> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        StringBuffer stringBuffer = new StringBuffer();
        // 前两个n表示左右括号的个数，第三个表示长度
        backtracing(res, stringBuffer, n, n, n);
        return res;
    }

    private void backtracing(List<String> res, StringBuffer stringBuffer,
                             int left, int right, int n) {
        if (stringBuffer.length() == n * 2) {
            res.add(new String(stringBuffer));
            return;
        }
        if (left > 0) {
            stringBuffer.append("(");
            backtracing(res, stringBuffer, left - 1, right, n);
            // 回溯
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }
        // 左括号必须比右括号多
        if (right > left) {
            stringBuffer.append(")");
            backtracing(res, stringBuffer, left, right - 1, n);
            // 回溯
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }
    }
}
